<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { timeFormat, toYuan, regYuanToFen, findParentsByChildValue, findCascader } from '@/hooks/util'
import cascader from '@/hooks/cascader.ts'
import * as accountApi from '@/api/account'
import * as fishApi from '@/api/fishGoods'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/store/modules/user'
import ImgView from './ImgView.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const imgViewRef = ref()
const spBizTypeStatus = ref(false)

const productedId = ref<string>()

const labelCol = {
  style: { width: '100px', textAlign: 'center' },
}
const wrapperCol = { span: 10 }

const formRef = ref()
interface formState {
  id?: string
  spBizType?: string
  categoryId?: string
  channelId?: string
  divisionId?: Array<string>
  robotId?: number
  images?: string
  sellingPrice?: number
  originalPrice?: number
  title?: string
  desc?: string
  inventory?: number
}
const formState = ref<formState>({})

import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateChangeBalance = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }
  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }
  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }
  // 如果一切正常，返回成功
  return Promise.resolve()
}

import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  spBizType: [{ required: true, message: '请选择行业名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品类目', trigger: 'blur' }],
  channelId: [{ required: true, message: '请选择商品渠道', trigger: 'blur' }],
  divisionId: [{ required: true, message: '请选择地区', trigger: 'blur' }],
  robotId: [{ required: true, message: '请选择店铺', trigger: 'blur' }],
  sellingPrice: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  originalPrice: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  desc: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  inventory: [{ required: true, message: '请输入库存', trigger: 'blur' }],
}

import type { SelectProps } from 'ant-design-vue'

// 行业名称
let spBizType = ref<string>('')
const industryList = ref<SelectProps['options']>([])
const selectIndustry = (selectValue: any) => {
  spBizType.value = selectValue as string
  getCategoryList(spBizType.value)
}

// 商品类目
let categoryId = ref<string>('')
const categoryList = ref<SelectProps['options']>([])
const selectCategory = (selectValue: any) => {
  categoryId.value = selectValue as string
  getChannelList(categoryId.value)
}

// 商品渠道
const channelList = ref<SelectProps['options']>([])

// 地区
let cascaderValue = ref<string[]>([])
const cascaderChange = (value: any, selectedOptions: any[]) => {
  cascaderValue.value = value
}
const filter = (inputValue: string, path: Option[]) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
}

const handleSubmit = async () => {
  formRef.value.validate().then(async () => {
    let param = {
      productId: formState.value.id,
      spBizType: formState.value.spBizType,
      categoryId: formState.value.categoryId,
      channelId: formState.value.channelId,
      divisionId: formState.value.divisionId[formState.value.divisionId.length - 1],
      robotId: formState.value.robotId,
      sellingPrice: regYuanToFen(Number(formState.value.sellingPrice), 100),
      originalPrice: regYuanToFen(Number(formState.value.originalPrice), 100),
      title: formState.value.title,
      desc: formState.value.desc,
      inventory: formState.value.inventory,
      imgList: imgList.value,
    }
    try {
      let { state, message: msg } = await fishApi.EditawayProduct(param)
      if (state === 200) {
        message.success('修改成功')
        router.go(-1)
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  })
}

// 获取行业
const getIndustryList = async () => {
  try {
    let { state, data, message: msg } = await fishApi.getSpBizType()
    if (state === 200) {
      industryList.value = data.map(item => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取类目
const getCategoryList = async (spBizTypeNum: string) => {
  try {
    let { state, data, message: msg } = await fishApi.getCategory({ spBizTypeNum })
    if (state === 200) {
      categoryList.value = data.map(item => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取渠道
const getChannelList = async (categoryNum: string) => {
  try {
    let { state, data, message: msg } = await fishApi.getChannel({ categoryNum })
    if (state === 200) {
      channelList.value = data.map(item => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
// 获取渠道
const getProductedDetail = async (id: any) => {
  try {
    let { state, data, message: msg } = await fishApi.getProductDetail({ id })
    if (state === 200) {
      formState.value.id = data.id
      formState.value.title = data.title
      formState.value.inventory = data.inventory
      formState.value.desc = data.desc
      formState.value.sellingPrice = Number(toYuan(data.sellingPrice))
      formState.value.originalPrice = Number(toYuan(data.originalPrice))
      imgList.value = data.imgList
      fileList.value = data.imgList.map(url => ({
        uid: Date.now() + Math.floor(Math.random() * 1000), // 为每个文件生成一个唯一的 id
        name: '文件名.jpg', // 你可以根据需要设置文件名
        url: url, // 这是图片的 URL
        status: 'done', // 表示文件已经上传完成
        type: 'image/jpeg', // 可以根据图片的实际类型设置
      }))
      formState.value.robotId = data.robotId
      spBizType.value = data.spBizType
      formState.value.spBizType = data.spBizType
      if (data.spBizType) {
        await getCategoryList(data.spBizType)
        categoryId.value = data.categoryId
        formState.value.categoryId = data.categoryId
        await getChannelList(data.categoryId)
        formState.value.channelId = data.channelId
      }
      spBizTypeStatus.value = true

      const result1 = await findParentsByChildValue(cascader, data.divisionId)
      const result2 = await findParentsByChildValue(cascader, result1.level1Value)    
      // cascaderChange([result2.level1Value, result1.level1Value, result1.level2Value], [])
      // formState.value.divisionId = [result2.level1Value, result1.level1Value, result1.level2Value]
      cascaderChange([result1.level1Value, result1.level2Value], [])
      formState.value.divisionId = [result1.level1Value, result1.level2Value]
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取闲鱼店铺
const robatList = ref([])

const handleChangeRadio = (e: any) => {
  console.log(e.target.value, 'ppp')
  formState.value.robotId = e.target.value
}
const getRobatList = async () => {
  const params = { currentPage: 1, pageSize: 100 }
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(params)
    if (state === 200) {
      robatList.value = data.list.map(item => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 商品图片
const imgList = ref<Array<string>>([])
interface FileItem {
  uid: string
  name?: string
  status?: string
}
const fileList = ref<FileItem[]>([])
const handleBeforeUpload = (file: any, fileList: any) => {
  return true
}

const customRequest = (option: any) => {
  const { onSuccess, onError, file, action, data = {} } = option
  const formData = new FormData()
  formData.append('file', file)
  fetch(action, {
    headers: {
      'User-Token': userStore.token,
    },
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(result => {
      onSuccess(result, file)
      if (result && result.data != null) {
        imgList.value.push(result.data)
      } else {
        message.error('图片太大，上传失败了')
      }
    })
    .catch(error => {
      message.error('图片太大，上传失败了')
      onError(error)
    })
}

// 预览图片
const handlePreview = async (file: any) => {
  if (file.url) {
    imgViewRef.value.showModal([file.url])
    return
  }
  if (file && file.response) {
    imgViewRef.value.showModal([file.response.data])
  } else {
    message.error('预览失败！')
  }
}

// 删除图片
const handleRemove = (file: any) => {
  if (file.url) {
    imgList.value = imgList.value.filter(item => item != file.url)
    return
  }
  if (file.status != 'error') {
    imgList.value = imgList.value.filter(item => item != file.response.data)
  }
}

interface FileInfo {
  file: FileItem
  fileList: FileItem[]
}
const handleChange = ({ fileList: newFileList }: FileInfo) => {
  fileList.value = newFileList.map(item => {
    if (item.response && item.response.result == false) {
      return {
        uid: '-5',
        name: 'image.png',
        status: 'error',
      }
    } else {
      return item
    }
  })
}

onMounted(() => {
  getIndustryList()
  getRobatList()

  const id = route.query.id
  if (route.query.id) {
    getProductedDetail(id)
  }
})
</script>

<template>
  <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll">
      <a-form
        ref="formRef"
        :rules="rules"
        :model="formState"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <div style="margin-bottom: 20px">
          <span class="titleFlag"></span>
          <span class="title">基本信息</span>
        </div>

        <a-form-item label="行业名称" name="spBizType">
          <a-select
            v-model:value="formState.spBizType"
            @change="selectIndustry"
            placeholder="行业名称"
            :disabled="spBizTypeStatus"
          >
            <a-select-option v-for="(item, index) in industryList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="商品类目" name="categoryId">
          <a-select
            v-model:value="formState.categoryId"
            @change="selectCategory"
            placeholder="商品类目"
          >
            <a-select-option v-for="(item, index) in categoryList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="商品渠道" name="channelId">
          <a-select v-model:value="formState.channelId" placeholder="商品渠道">
            <a-select-option v-for="(item, index) in channelList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="地区" name="divisionId">
          <a-cascader
            v-model:value="formState.divisionId"
            :options="cascader"
            :show-search="{ filter }"
            @change="cascaderChange"
            placeholder="地区"
          />
        </a-form-item>

        <div style="margin-bottom: 20px">
          <span class="titleFlag"></span>
          <span class="title">发布的闲鱼店铺</span>
        </div>

        <a-form-item label="闲鱼店铺" name="robotId">
          <a-radio-group
            v-model:value="formState.robotId"
            :options="robatList"
            @change="handleChangeRadio"
            class="selectShop"
          />
        </a-form-item>

        <div style="margin-bottom: 20px">
          <span class="titleFlag"></span>
          <span class="title">商品信息</span>
        </div>

        <a-form-item has-feedback name="images" label="商品图片">
          <a-upload
            :multiple="true"
            list-type="picture-card"
            action="http://crm.liangpiaovip.com/platform/wechatReply/uploadToAliOss"
            :show-upload-list="{ showRemoveIcon: true }"
            :beforeUpload="handleBeforeUpload"
            :customRequest="customRequest"
            @preview="handlePreview"
            @remove="handleRemove"
            @change="handleChange"
            :file-list="fileList"
          >
            <upload-outlined></upload-outlined>
            上传图片
          </a-upload>
        </a-form-item>

        <a-form-item label="商品标题" name="title">
          <a-input v-model:value="formState.title"></a-input>
        </a-form-item>

        <a-form-item label="描述" name="desc">
          <a-textarea
            v-model:value="formState.desc"
            style="width: 500px; max-height: 260px"
            :maxlength="5000"
          ></a-textarea>
        </a-form-item>

        <a-form-item has-feedback label="售价" name="sellingPrice">
          <a-input-number
            v-model:value="formState.sellingPrice"
            style="width: 70%"
          ></a-input-number>
        </a-form-item>

        <a-form-item has-feedback label="原价" name="originalPrice">
          <a-input-number
            v-model:value="formState.originalPrice"
            style="width: 70%"
          ></a-input-number>
        </a-form-item>

        <a-form-item has-feedback label="库存" name="inventory">
          <a-input-number v-model:value="formState.inventory" style="width: 70%"></a-input-number>
        </a-form-item>

        <a-form-item style="text-align: center">
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <ImgView ref="imgViewRef"></ImgView>
  </page-container>
</template>

<style scoped lang="less">
.titleFlag {
  display: inline-block;
  width: 4px;
  height: 16px;
  margin-right: 4px;
  background-color: #7417be;
  border-radius: 2px;
}

.title {
  font-weight: bold;
  font-size: 16px;
}

.shop {
  display: inline-block;
  padding: 0 10px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  border: 1px solid #ebebeb;
  margin-right: 10px;
  margin-bottom: 5px;
}

/deep/ .ant-checkbox-group-item {
  padding: 0 10px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  border: 1px solid #ebebeb;
  margin-right: 10px;
  margin-bottom: 5px;
}

/deep/ .ant-checkbox-inner,
.ant-checkbox-input {
  border-radius: 50%;
}
</style>
